/*
 * Socket.cpp
 *
 *  PEREIRA, FERNANDO ROQUE
 *  91610
 */

#include "Socket.h"
#include <unistd.h>

Socket::Socket() {
	this->sockFd = socket(AF_INET, SOCK_STREAM, 0);
}

Socket::~Socket() {
	this->cerrarSocket();
}

void Socket::setAddr_in(unsigned int numPuerto, const char* ip) {
	this->sockAddr.sin_family = AF_INET;
	this->sockAddr.sin_port = htons(numPuerto);

	if (!ip) {
		// ip = NULL, busca en todos (server)
		this->sockAddr.sin_addr.s_addr = INADDR_ANY;
	} else {
		this->sockAddr.sin_addr.s_addr = inet_addr(ip);
	}
	memset(&(this->sockAddr.sin_zero), 0, sizeof(this->sockAddr.sin_zero));
}

int Socket::sendMessage(int sockFd, const void* message, unsigned int tamMessage) {
	return (send(sockFd, message, tamMessage, 0));
}

int Socket::sendMessage(const void* message, unsigned int tamMessage) {
	//std::cout << "send message socket" << std::endl;
	int ret = send(this->sockFd, message, tamMessage, 0);
	//std::cout << "ret: "<< ret << std::endl;
	return ret;
}

int Socket::receiveMessage(int sockFd, void* mensajeRecibido, size_t len) {
	return (recv(sockFd, mensajeRecibido, len, 0));
}

int Socket::receiveMessage(void* mensajeRecibido, size_t len) {
	return (recv(this->sockFd, mensajeRecibido, len, 0));
}

struct sockaddr_in Socket::getSockAddr() {
	return (this->sockAddr);
}

int Socket::cerrarSocket() {
	this->shutDownSocket();
	return(close(this->sockFd));
}

int Socket::shutDownSocket() {
	return(shutdown(this->sockFd, 2));
}

unsigned int Socket::getSockPort(){
	socklen_t len = sizeof sockAddr;
	getsockname(sockFd, (struct sockaddr*) &sockAddr, &len);
	return ntohs(sockAddr.sin_port);
}

unsigned int Socket::getPeerPort(){
	socklen_t len = sizeof sockAddr;
	getpeername(sockFd, (struct sockaddr*) &sockAddr, &len);
	return ntohs(sockAddr.sin_port);
}
